package com.atguigu.java1;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 1.客户端给服务端发送文本，
 * 服务端会将文本转成大写在返回给客户端。
 */
public class TCPTest4 {
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("100.78.71.245"), 8989);

        OutputStream os = socket.getOutputStream();

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("hello.txt")));
        byte[] buffer = new byte[5];
        int len;
        while ((len = bis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        socket.shutdownOutput();

        InputStream is = socket.getInputStream();
        BufferedOutputStream baos = new BufferedOutputStream(new FileOutputStream(new File("hello2.txt")));
        byte[] buffer2 = new byte[5];
        int len2;
        while ((len2 = is.read(buffer2)) != -1){
            String str = new String(buffer2);
            str.toUpperCase();
            baos.write(str.getBytes(),0,len2);
        }
        baos.close();
        is.close();
        bis.close();
        os.close();
        socket.close();

    }

    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(8989);
        Socket socket = ss.accept();
        InputStream is = socket.getInputStream();
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("hello2.txt")));
        byte[] buffer = new byte[5];
        int len;
        while ((len = is.read(buffer)) != -1){
            String str = new String(buffer);
            str.toUpperCase();
            bos.write(str.getBytes(),0,len);
        }

        OutputStream os = socket.getOutputStream();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("hello2.txt")));
        byte[] buffer1 = new byte[5];
        int len1;
        while ((len1 = bis.read(buffer1)) != -1){
           String str = new String(buffer1);
           str.toUpperCase();
           os.write(str.getBytes(),0,len1);
        }

        bis.close();
        os.close();
        is.close();
        bos.close();
        ss.close();
        socket.close();
    }
}
